package ran.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ran.entity.OptionInfo;
import ran.entity.PageRequest;
import ran.entity.QuestionInfo;
import ran.entity.ResponseResult;
import ran.mapper.OptionMapper;
import ran.mapper.QuestionMapper;
import ran.service.Optionservice;
import ran.service.QuestionService;

import java.io.InputStream;
import java.util.List;

/**
 * Excel导入实现类
 */
@Slf4j
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, QuestionInfo> implements QuestionService{

    @Autowired
    private OptionMapper optionMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private Optionservice optionservice;

    @Override
    public void importFromExcel(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(inputStream);

        // === Sheet1: Question ===
        Sheet questionSheet = workbook.getSheetAt(0);
        for (int i = 1; i <= questionSheet.getLastRowNum(); i++) {
            Row row = questionSheet.getRow(i);
            if (row == null) continue;

            QuestionInfo q = new QuestionInfo();
            q.setQuestionId((long) row.getCell(0).getNumericCellValue());
            q.setContent(row.getCell(1).getStringCellValue());
            q.setQuestionType(row.getCell(2).getStringCellValue());
            q.setCorrectAnswer(row.getCell(3).getStringCellValue());
            q.setRiskLabel(row.getCell(4).getStringCellValue());
            q.setCheatType(row.getCell(5).getStringCellValue());
            q.setHighRiskOption(row.getCell(6).getStringCellValue());
            q.setRiskScore(row.getCell(7).getNumericCellValue());
            q.setGrade((int) row.getCell(8).getNumericCellValue());

            this.saveOrUpdate(q, new LambdaQueryWrapper<QuestionInfo>().eq(QuestionInfo::getQuestionId, q.getQuestionId()));
        }

        // === Sheet2: Option ===
        optionservice.importFromExcel(workbook);
        workbook.close();
    }

    @Override
    public ResponseResult<QuestionInfo> getListByPage(PageRequest pageRequest) {
        Long count = questionMapper.selectCount(new LambdaQueryWrapper<QuestionInfo>().ne(QuestionInfo::getQuestionId,0));
        log.info("题目总数, count:{}",count);
        List<QuestionInfo> list = questionMapper.selectBookByPage(pageRequest);
        for (QuestionInfo questionInfo:list) {
            List<OptionInfo> options = optionMapper.selectList(new LambdaQueryWrapper<OptionInfo>()
                    .eq(OptionInfo::getQuestionId,questionInfo.getQuestionId()));
            questionInfo.setOptions(options);
        }
        return new ResponseResult<>(count,list,pageRequest);
    }

    @Override
    public QuestionInfo queryQuestionById(Integer questionId) {
        try {
            QuestionInfo questionInfo = questionMapper.selectOne(new LambdaQueryWrapper<QuestionInfo>().eq(QuestionInfo::getQuestionId, questionId));
            List<OptionInfo> options = optionMapper.selectList(new LambdaQueryWrapper<OptionInfo>()
                    .eq(OptionInfo::getQuestionId,questionInfo.getQuestionId()));
            questionInfo.setOptions(options);
            return questionInfo;
        }catch (Exception e) {
            log.error("queryQuestionById 出现错误, e:",e);
            return null;
        }

    }

    @Override
    public boolean updateBook(QuestionInfo questionInfo) {
        try {
            questionMapper.update(questionInfo,new LambdaQueryWrapper<QuestionInfo>().eq(QuestionInfo::getQuestionId,questionInfo.getQuestionId()));
            List<OptionInfo> options = questionInfo.getOptions();
            for (OptionInfo option : options) {
                optionMapper.update(option,new LambdaQueryWrapper<OptionInfo>()
                        .eq(OptionInfo::getQuestionId,questionInfo.getQuestionId())
                        .eq(OptionInfo::getOptionKey,option.getOptionKey()));
            }
            return true;
        }catch (Exception e) {
            log.error("更新出现错误, e:",e);
            return false;
        }

    }

    @Override
    public boolean deleteQuestion(Long questionId) {
        try {
            questionMapper.deleteById(questionId);
            return true;
        }catch (Exception e) {
            log.error("删除失败, e:",e);
            return false;
        }
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        questionMapper.deleteBatchIds(ids);
    }

}
